package com.boronstream.istar;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar.LayoutParams;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.boronstream.istar.FragmentMonth.MonthFragment;
import com.boronstream.istar.FragmentToday.TodayFragment;
import com.boronstream.istar.FragmentTomorrow.TomorrowFragment;
import com.boronstream.istar.FragmentWeek.WeekFragment;
import com.boronstream.istar.FragmentYear.YearFragment;
import com.boronstream.istar.S.IActivityMain;
import com.boronstream.istar.S.IItemHeader;
import com.boronstream.istar.S.IItemMenu;
import com.boronstream.istar.S.IItemWindowStars;
import com.boronstream.istar.http.PlayRequestListener;
import com.boronstream.istar.http.PlayResponse;
import com.boronstream.istar.http.response.IBasicResponse;
import com.boronstream.istar.http.response.IPhoneAppResponse;
import com.boronstream.istar.utils.CommonDefine;
import com.boronstream.istar.utils.CommonDefine.IntentAction;
import com.boronstream.istar.utils.CommonDefine.TimeExtra;
import com.boronstream.istar.utils.HelperUtils;
import com.boronstream.istar.utils.Logger;
import com.boronstream.istar.view.adapter.AdapterStar.MyFragment;
import com.tencent.exmobwin.MobWINManager;
import com.tencent.exmobwin.Type;
import com.tencent.exmobwin.banner.AdListener;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.NotificationType;
import com.umeng.fb.UMFeedbackService;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;

public class MainActivity extends FragmentActivity implements
		PlayRequestListener, OnClickListener {

	private static final String TAG = MainActivity.class.getSimpleName();

	private IActivityMain self;

	private String currentStar;

	private PopupWindow mPopupWindow;
	private View mConvertView;
	private FilterAdapter adapter;

	private StarAdapter starAdapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		MobclickAgent.onError(this);
		UmengUpdateAgent.update(this);
		MobWINManager.init(this, Type.MOBWIN_BANNER);
		self = new IActivityMain(this);
		SharedPreferences sp = getSharedPreferences(
				getString(R.string.app_name), MODE_PRIVATE);
		currentStar = sp.getString("default_star",
				getString(R.string.default_star));
		self.mTitle.setText(currentStar);

		/**
		 * init
		 */
		initThreme();
		SharedPreferences sPreferences = getSharedPreferences(
				getString(R.string.app_name), MODE_PRIVATE);
		boolean first = sPreferences.getBoolean("first_init", true);

		/**
		 * Filter for stars
		 */
		final String[] fiStrings = getResources().getStringArray(
				R.array.star_list);
		final String[] dateList = getResources().getStringArray(
				R.array.star_data_list);
		adapter = new FilterAdapter(fiStrings, dateList);
		LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		mConvertView = inflater.inflate(R.layout.i_item_window_stars, null);
		IItemWindowStars windowView = new IItemWindowStars(mConvertView);
		windowView.mStarsListView
				.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						currentStar = fiStrings[position];
						self.mTitle.setText(currentStar);
						refreshAstroImage();
						SharedPreferences sp = getSharedPreferences(
								getString(R.string.app_name), MODE_PRIVATE);
						Editor editor = sp.edit();
						editor.putString("default_star", currentStar);
						editor.commit();
						mPopupWindow.dismiss();
						MobclickAgent.onEvent(MainActivity.this,
								"default_star", currentStar);
						adapter.notifyDataSetChanged();
						sendBroadCast();
					}

				});

		windowView.mStarsListView
				.setSelector(R.drawable.selector_listview_selection);
		windowView.mStarsListView.setAdapter(adapter);

		mPopupWindow = makePopupWindow(MainActivity.this);
		self.mTitle.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				mPopupWindow.showAsDropDown(self.mTitle);
			}
		});
		if (first) {
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					mPopupWindow.showAsDropDown(self.mTitle);
				}
			}, TimeExtra.ONE_SECOND);
		}

		/**
		 * ActionBar and menus
		 */
		String[] actions = getResources().getStringArray(R.array.star_actions);
		starAdapter = new StarAdapter(getSupportFragmentManager(), actions);
		ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
		// self.mViewPager.setAdapter(starAdapter);
		viewPager.setAdapter(starAdapter);
		// self.mPagerTabStrip.setTextColor(getResources().getColor(R.color.selected_text));
		self.mPagerTabStrip.setTabIndicatorColor(getResources().getColor(
				R.color.selected_text));
		self.mPagerTabStrip.setDrawFullUnderline(true);
		self.mPagerTabStrip.setTextSpacing(50);

		self.mImgShare.setOnClickListener(this);
		self.mImgMemu.setOnClickListener(this);

		/**
		 * Icon
		 */
		this.refreshAstroImage();
		self.mProgressBar1.setVisibility(View.GONE);
		/**
		 * Adview
		 */

		if (first) {
			self.mAdview.setVisibility(View.GONE);
		}
		self.mImgX.setVisibility(View.GONE);
		self.mTadview.setAdListener(new AdListener() {

			@Override
			public void onReceiveFailed(int arg0) {
			}

			@Override
			public void onReceiveAd() {
				new Handler().postDelayed(new Runnable() {

					@Override
					public void run() {
						self.mImgX.setVisibility(View.VISIBLE);
					}
				}, TimeExtra.ONE_SECOND * 2);
			}
		});
		this.initShortCut();
	}

	private void initShortCut() {
		SharedPreferences sPreferences = getSharedPreferences(
				getString(R.string.app_name), MODE_PRIVATE);
		boolean first = sPreferences.getBoolean("first_init", true);
		Editor editor = sPreferences.edit();
		if (first) {
			delShortcut();
			addShortcut();
		}
		editor.putBoolean("first_init", false);
		editor.commit();
	}

	@Override
	public void onRequestFinished(ResultType resultType, PlayResponse response) {
		Log.d(TAG, "code:" + response.getStatusCode() + "resultType:"
				+ resultType);
		if (resultType == ResultType.SUCCESS && response != null
				&& response instanceof IBasicResponse) {
			IBasicResponse iBasicResponse = (IBasicResponse) response;
			Log.i(TAG, "bodyContent:" + iBasicResponse.getBodyContent());
		}

		if (resultType == ResultType.SUCCESS && response != null
				&& response instanceof IPhoneAppResponse) {
			IPhoneAppResponse iappResponse = (IPhoneAppResponse) response;
			Log.i(TAG, "appContent:" + iappResponse.getBodyContent());
		}
	}

	private class FilterAdapter extends BaseAdapter {
		String[] filters;

		String[] dateList;

		public FilterAdapter(String[] filters, String[] dateList) {
			this.filters = filters;
			this.dateList = dateList;
		}

		@Override
		public int getCount() {
			return filters.length;
		}

		@Override
		public Object getItem(int arg0) {
			return filters[arg0];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			IItemHeader header;
			if (convertView == null) {
				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.i_item_header, null);
				header = new IItemHeader(convertView);
				convertView.setTag(header);
			} else {
				header = (IItemHeader) convertView.getTag();
			}
			if (currentStar != null
					&& currentStar.toString().startsWith(filters[position])) {
				header.mText.setTextColor(getResources().getColor(
						R.color.selected_text));
				header.mImgSelected.setVisibility(View.VISIBLE);
			} else {
				header.mText.setTextColor(Color.WHITE);
				header.mImgSelected.setVisibility(View.GONE);
			}
			header.mText.setText(filters[position] + "(" + dateList[position]
					+ ")");
			return convertView;
		}

	}

	private void refreshAstroImage() {
		if (currentStar != null) {
			String[] astros = getResources().getStringArray(R.array.star_list);
			for (int i = 0; i < astros.length; i++) {
				if (currentStar.equals(astros[i])) {
					String name = "star_" + i;
					self.mIcon.setImageResource(HelperUtils.getInstance()
							.getDrawableIdByName(MainActivity.this, name));
					break;
				}
			}
		}
	}

	private PopupWindow makePopupWindow(Context cx) {
		PopupWindow mPopupWindow = new PopupWindow(cx);
		mPopupWindow.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.dark_header));
		mPopupWindow.setContentView(mConvertView);
		mPopupWindow.setWidth(LayoutParams.MATCH_PARENT);
		mPopupWindow.setHeight(LayoutParams.MATCH_PARENT);
		mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.setFocusable(true);
		mPopupWindow.setTouchable(true);
		return mPopupWindow;
	}

	private class MenuAdapter extends BaseAdapter {
		String[] filters;

		public MenuAdapter(String[] filters) {
			this.filters = filters;
		}

		@Override
		public int getCount() {
			return filters.length;
		}

		@Override
		public Object getItem(int arg0) {
			return filters[arg0];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			IItemMenu header;
			if (convertView == null) {
				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.i_item_menu, null);
				header = new IItemMenu(convertView);
				convertView.setTag(header);
			} else {
				header = (IItemMenu) convertView.getTag();
			}
			header.mText.setTextColor(Color.WHITE);
			header.mText.setText(filters[position]);
			return convertView;
		}

	}

	private PopupWindow makeMenuWindow(Context cx) {
		final PopupWindow mPopupWindow = new PopupWindow(cx);
		mPopupWindow.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.dark_header));
		ListView listView = new ListView(this);
		listView.setCacheColorHint(getResources().getColor(R.color.transparent));
		listView.setFadingEdgeLength(0);
		final String[] menuStrings = new String[5];
		menuStrings[0] = "换换背景";
		menuStrings[1] = "给个好评";
		menuStrings[2] = "检查更新";
		menuStrings[3] = "意见反馈";
		menuStrings[4] = "退出系统";
		listView.setSelector(R.drawable.selector_listview_selection);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long id) {
				mPopupWindow.dismiss();
				MobclickAgent.onEvent(MainActivity.this, "home_setting",
						menuStrings[position]);
				if (position == 0) {
					List<Integer> bgs = new ArrayList<Integer>();
					bgs.add(R.drawable.temp);
					bgs.add(R.drawable.astro_mate_main_bg);
					bgs.add(R.drawable.shape_bg_gray);
					bgs.add(R.drawable.dark_header);
					bgs.add(R.drawable.bg_repeat);

					SharedPreferences sPreferences = getSharedPreferences(
							getString(R.string.app_name), MODE_PRIVATE);
					int currentBg = sPreferences.getInt("default_bg",
							R.drawable.bg_repeat);

					List<Integer> newList = new ArrayList<Integer>();
					for (int i = 0; i < bgs.size(); i++) {
						if (currentBg == bgs.get(i)) {
						} else {
							newList.add(bgs.get(i));
						}
					}

					Editor editor = sPreferences.edit();
					editor.putInt("default_bg", newList.get((int) (System
							.currentTimeMillis() % newList.size())));
					editor.commit();
					initThreme();
				}

				if (position == 1) {
					try {
						Uri uri = Uri.parse("market://details?id="
								+ getPackageName());
						Logger.i(TAG, "package:" + getPackageName());
						Intent intent = new Intent(Intent.ACTION_VIEW, uri);
						startActivity(intent);
					} catch (Exception e) {
					}
				} else if (position == 2) {
					checkUpdate();
				} else if (position == 3) {
					UMFeedbackService.openUmengFeedbackSDK(MainActivity.this);
				} else if (position == 4) {
					finish();
				}
			}
		});
		MenuAdapter menuAdapter = new MenuAdapter(menuStrings);
		listView.setAdapter(menuAdapter);
		mPopupWindow.setContentView(listView);
		mPopupWindow.setWidth((int) (getResources().getDimension(
				R.dimen.action_bar_default_height) * 2.5));
		mPopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
		mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.setFocusable(true);
		mPopupWindow.setTouchable(true);
		mPopupWindow.showAsDropDown(self.mImgMemu);

		return mPopupWindow;
	}

	private void initThreme() {

		SharedPreferences sPreferences = getSharedPreferences(
				getString(R.string.app_name), MODE_PRIVATE);
		int currentBg = sPreferences.getInt("default_bg", R.drawable.bg_repeat);
		self.mRootLayout.setBackgroundResource(currentBg);
	}

	private void checkUpdate() {
		UmengUpdateAgent.update(this);
		UmengUpdateAgent.setUpdateAutoPopup(false);
		UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
			@Override
			public void onUpdateReturned(int updateStatus,
					UpdateResponse updateInfo) {
				switch (updateStatus) {
				case 0: // has update
					UmengUpdateAgent.showUpdateDialog(MainActivity.this,
							updateInfo);
					break;
				case 1: // has no update
					Toast.makeText(MainActivity.this, "没有更新",
							Toast.LENGTH_SHORT).show();
					break;
				case 2: // none wifi
					Toast.makeText(MainActivity.this, "没有wifi连接， 只在wifi下更新",
							Toast.LENGTH_SHORT).show();
					break;
				case 3: // time out
					Toast.makeText(MainActivity.this, "超时", Toast.LENGTH_SHORT)
							.show();
					break;
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		Logger.d(TAG, "onCreateOptionsMenu");
		makeMenuWindow(this);
		return true;
	}

	private void shot() {
		try {
			View view = getWindow().getDecorView();
			Display display = this.getWindowManager().getDefaultDisplay();
			DisplayMetrics outMetrics = new DisplayMetrics();
			display.getMetrics(outMetrics);
			view.layout(0, 0, outMetrics.widthPixels, outMetrics.heightPixels);
			view.setDrawingCacheEnabled(true);// 允许当前窗口保存缓存信息，这样getDrawingCache()方法才会返回一个Bitmap
			Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache());
			new File(CommonDefine.APP_SDCARD_FOLDER).mkdirs();
			File file = new File(CommonDefine.APP_SDCARD_FOLDER + "/share.png");
			if (file.exists()) {
				file.delete();
			}
			file.createNewFile();
			OutputStream outStream = new FileOutputStream(file);
			bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
			outStream.flush();
			outStream.close();
		} catch (Exception e) {
			Logger.e(TAG, "exception:" + e.getMessage());
			e.printStackTrace();
		}
	}

	private void share() {
		MobclickAgent.onEvent(this, "share", "main");
		MobclickAgent.onEvent(this, "share", "main" + currentStar);
		Intent intent = new Intent(Intent.ACTION_SEND);
		File file = new File(CommonDefine.APP_SDCARD_FOLDER + "/share.png");
		intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
		intent.setType("image/*");
		intent.putExtra(Intent.EXTRA_SUBJECT, currentStar + "星座运势");
		intent.putExtra(Intent.EXTRA_TEXT, currentStar + "星座运势");
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(Intent.createChooser(intent, getTitle()));

	}

	@Override
	public void onClick(View v) {
		if (v.getId() == self.mImgShare.getId()) {
			Message msg = new Message();
			msg.what = MSG_SHARE_CONTENT;
			handler.sendMessageDelayed(msg, TimeExtra.ONE_SECOND / 2);
		}
		if (v.getId() == self.mImgMemu.getId()) {
			makeMenuWindow(this);
		}
	}

	private final int MSG_SHARE_CONTENT = 100;
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == MSG_SHARE_CONTENT) {
				shot();
				share();
			}
		};
	};

	private void sendBroadCast() {
		try {
			Intent intent = new Intent();
			intent.setAction(IntentAction.ACTION_STAR_FILTER_CHANGE);
			sendBroadcast(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static class StarAdapter extends FragmentStatePagerAdapter {

		private static final String TAG = StarAdapter.class.getSimpleName();
		private String[] titles;

		public StarAdapter(FragmentManager fm, String[] titles) {
			super(fm);
			this.titles = titles;
		}

		@Override
		public Fragment getItem(int position) {
			Logger.d(TAG, "getPosition:" + position);
			if (position == 0) {
				return TodayFragment.newInstance();
			}
			if (position == 1) {
				return TomorrowFragment.newInstance();
			}
			if (position == 2) {
				return WeekFragment.newInstance();
			}
			if (position == 3) {
				return MonthFragment.newInstance();
			}
			if (position == 4) {
				return YearFragment.newInstance();
			}
			return MyFragment.newInstance();
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return titles[position];
		}

		@Override
		public int getCount() {
			return titles.length;
		}
	}

	/**
	 * 为程序创建桌面快捷方式
	 */
	private void addShortcut() {
		try {

			Intent shortcut = new Intent(
					"com.android.launcher.action.INSTALL_SHORTCUT");

			// 快捷方式的名称
			shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,
					getString(R.string.app_name));
			shortcut.putExtra("duplicate", false); // 不允许重复创建

			// 指定当前的Activity为快捷方式启动的对象: 如 com.everest.video.VideoPlayer
			// 注意: ComponentName的第二个参数必须加上点号(.)，否则快捷方式无法启动相应程序
			ComponentName comp = new ComponentName(this.getPackageName(), "."
					+ this.getLocalClassName());
			shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(
					Intent.ACTION_MAIN).setComponent(comp));

			// 快捷方式的图标
			ShortcutIconResource iconRes = Intent.ShortcutIconResource
					.fromContext(this, R.drawable.ic_launcher);
			shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);

			sendBroadcast(shortcut);
		} catch (Exception e) {
		}

	}

	private boolean hasShortcut() {
		boolean isInstallShortcut = false;
		try {
			final ContentResolver cr = getContentResolver();
			final String AUTHORITY = "com.android.launcher.settings";
			final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
					+ "/favorites?notify=true");
			Cursor c = cr.query(CONTENT_URI, new String[] { "title",
					"iconResource" }, "title=?",
					new String[] { getString(R.string.app_name).trim() }, null);
			if (c != null && c.getCount() > 0) {
				isInstallShortcut = true;
			}
			return isInstallShortcut;
		} catch (Exception e) {
		}
		return isInstallShortcut;
	}

	private void delShortcut() {
		try {
			Intent shortcut = new Intent(
					"com.android.launcher.action.UNINSTALL_SHORTCUT");

			// 快捷方式的名称
			shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,
					getString(R.string.app_name));

			// 指定当前的Activity为快捷方式启动的对象: 如 com.everest.video.VideoPlayer
			// 注意: ComponentName的第二个参数必须是完整的类名（包名+类名），否则无法删除快捷方式
			String appClass = this.getPackageName() + "."
					+ this.getLocalClassName();
			ComponentName comp = new ComponentName(this.getPackageName(),
					appClass);
			shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(
					Intent.ACTION_MAIN).setComponent(comp));

			sendBroadcast(shortcut);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		UMFeedbackService.enableNewReplyNotification(this,
				NotificationType.AlertDialog);
	}

	public void closeAd(View view) {
		System.out.println("Adview onClick");
		self.mAdview.setVisibility(View.GONE);
		MobclickAgent.onEvent(MainActivity.this, "home_adview_close",
				currentStar);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onDestroy() {
		MobWINManager.destroy();
		super.onDestroy();
	}
}
